var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.parent.frames["zwIframe"];
if (!upWindow) {
    upWindow = window.parent.parent.frames["componentDiv"].frames["zwIframe"];
}
function fy_dialog_close() {
    window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
}

function getUpFields(name) {
    return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
    return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function getUpAccountFieldValue(name) {
    var field = getUpFields(name).eq(0);
    return {
        displayValue: field.is("span") ? field.text() : field.val(),
        value: eval("(" + field.parent("span").attr("fieldVal") + ")").value
    };
}

function getUpFieldValue(field) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var browseTag = field.hasClass(browseClass);
    var addTag = field.hasClass(addClass);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }
    var obj = new Object();
    obj.displayName = fieldVal.displayName;
    obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "checkbox":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "radio":
            if (editTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            }
            break;
        case "select":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + " option:selected")
                        .text();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).attr("val4cal");
            }
            
            break;
        case "date":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
                if (obj.value != "") {
                    obj.value = obj.value + " 00:00";
                }
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "datetime":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "flowdealoption":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "lable":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relationform":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relation":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "project":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
//                obj.value = field.find("#" + fieldVal.name + "_txt").val();
//                obj.id = field.find("#" + fieldVal.name).val().split('|')[1];
                obj.value = field.find("#" + fieldVal.name).val().split('|')[1];
            } else if (browseTag) {
//                obj.value = field.find("#" + fieldVal.name).text();
                obj.value = fieldVal.value;
            }
            break;
//            if (editTag) {
//                obj.value = field.find("#" + fieldVal.name + "_txt").val();
//            } else if (browseTag) {
//                obj.value = field.find("#" + fieldVal.name).text();
//            }
//            break;
        case "attachment":
        case "image":
        case "document":
            if (editTag || browseTag) {
                var attNames = "";
                var tempField = field.find("#" + fieldVal.name);
                var tempFileId = "";
                if (tempField[0].tagName.toLowerCase() == "input") {
                    tempFileId = tempField.val();
                } else if (tempField[0].tagName.toLowerCase() == "span") {
                    tempFileId = tempField[0].innerHTML;
                }
                var atts = upWindow.getAttBySubreference(tempFileId);
                for (var j = 0; j < atts.length; j++) {
                    attNames += atts[j].filename + ",";
                }
                if (attNames != "") {
                    attNames = attNames.substr(0, attNames.length - 1);
                }
                obj.value = attNames;
            }
            break;
        case "outwrite":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "externalwrite-ahead":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "exchangetask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "querytask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        default:
            tag = false;
    }
    if (obj.value != undefined) {
        obj.value = obj.value.replace("\r\n", ";");
        obj.value = obj.value.replace("\n", ";");
    }
    return obj;
}
function setUpFieldValue(name, value) {
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
            value);
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
            .trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {

    try {

        var fieldVal = field.attr("fieldVal");
        var editTag = field.hasClass(editClass);
        var addTag = field.hasClass(addClass);
        value = trim(value);
        displayValue = trim(displayValue);
        if (fieldVal != null && typeof (fieldVal) != 'undefined') {
            fieldVal = eval("(" + fieldVal + ")");
        } else {
            return null;
        }

// var obj = new Object();
// obj.displayName = fieldVal.displayName;
// obj.name = fieldVal.name;
        var tag = true;
        switch (fieldVal.inputType) {
            case "text":
            case "textarea":
                if (editTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    // inField.attr("readonly", true);
                    inField.trigger("blur");
                } else if (addTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    // inField.attr("readonly", true);
                    inField.trigger("blur");
                }
                break;
            case "checkbox":
                if (editTag) {
                    field.find("#" + fieldVal.name).attr("checked", true);
                    field.find("#" + fieldVal.name).trigger("click");
                }
                break;
            case "radio":
                if (editTag) {
                    field.find(":radio").eq(index).attr("checked", true);
                    field.find(":radio").eq(index).trigger("click");
                }
                break;
            case "select":
                if (editTag) {
// if (value) {
// field.find("#" + fieldVal.name).value(value);
// } else {
                    var options = field.find("#" + fieldVal.name + " option");
                    for (var k = 0; k < options.length; k++) {
                        if (options.eq(k).text() == value)
                            options.eq(k).attr("selected", true);
                    }
// }
                    field.find("#" + fieldVal.name).trigger("change");
                }
                break;
            case "date":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "datetime":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "member":
            case "multimember":
            case "account":
            case "multiaccount":
            case "department":
            case "multidepartment":
            case "post":
            case "multipost":
            case "level":
            case "multilevel":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                }
                break;
        }
    } catch (e) {
// TODO: handle exception
    }
}

/**
 * 去除左右空格
 */
function trim(str) {
    return (str) ? (typeof str == "string" ? str.replace(/^\s*/, "").replace(
            /\s*$/, "") : str) : "";
}
function getParentTR(dom) {
    if (dom) {
        if (dom.tagName.toLowerCase() == 'tr') {
            return dom;
        } else {
            return getParentTR(dom.parentNode);
        }
    } else {
        return null;
    }
}

function _ajax(url, operate) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
        	alert(xmlhttp.status);
            if (xmlhttp.status == 200) {           	
                text = xmlhttp.responseText;
                operate(eval("(" + text + ")"));
            } else {
                alert("连接服务器异常");
            }
        }
    };
    xmlhttp.open("get", url + "&temp=" + Math.random(), true);
    xmlhttp.send();
}

function writeField(rows) {
    for (var i = 0; i < rows.length; i++) {
        for (var key in rows[i]) {
            try {
                if (rows[i][key].indexOf("[") == 0
                        && rows[i][key].lastIndexOf("]") == (rows[i][key].length - 1)) {
                    var tempArray = eval("(" + rows[i][key] + ")");
                    setUpFieldValue2(getUpFieldsByFieldval(key).eq(0),
                            tempArray[1], tempArray[0]);
                } else {
                    var fields = getUpFieldsByFieldval(key);
                    for (var t = 0; t < fields.length; t++)
                        setUpFieldValue2(fields.eq(t), rows[i][key]);
                }
            } catch (e) {
            }
        }
    }
}
function resetFields(fields) {
    fields = eval("(" + fields + ")");
    if (fields.repeat) {
        for (var i = 0; i < fields.repeat.length; i++) {
            var fieldNameArray = fields.repeat[i];
            for (var j = 0; j < fieldNameArray.length; j++) {
                var repeatFields = getUpFieldsByFieldval(fieldNameArray[j]);
                var repeatCount = repeatFields.length;
                if (repeatCount > 0) {
                    if (repeatCount > 1) {
                        var tbody = repeatFields.eq(0).parent();
                        while (!tbody.is("tbody")) {
                            tbody = tbody.parent();
                        }
                        for (var k = repeatCount - 1; k >= 1; k--) {
                            if (repeatFields.eq(k)
                                    && repeatFields.eq(k).parent("tr")) {
                                upWindow.fy_delCurrentRepeat(tbody.children()
                                        .last());
                            }
                        }
                        repeatCount = 1;
                    }
                    setUpFieldValue2(repeatFields.eq(0), "");
                }
            }
        }
    }
    if (fields.setNull) {
        for (var i = 0; i < fields.setNull.length; i++) {
            var fieldNameArray = getUpFieldsByFieldval(fields.setNull[i]);
            for (var j = 0; j < fieldNameArray.length; j++) {
                setUpFieldValue2(fieldNameArray.eq(j), "");
            }
        }
    }
    for (var i = 0; i < fields.comm.length; i++) {
        var commFields = getUpFieldsByFieldval(fields.comm[i]);
        for (var t = 0; t < commFields.length; t++)
            if (commFields.eq(t)) {
                setUpFieldValue2(commFields.eq(t), "")
            }
    }
}
function writeRepeatTableField(rows) {
    var fieldName;
    for (var key in rows[0]) {
        try {
            if (getUpFieldsByFieldval(key).length > 0) {
                fieldName = key;
                break;
            }
        } catch (e) {
        }
    }
    if (fieldName && !rows[0].QUERYFIELDNAME) {
        var fieldArray = getUpFieldsByFieldval(fieldName);
        var oldLength = fieldArray.length;
        var firstField = fieldArray.eq(0);
        var realName = getUpFieldValue(firstField);
        var tbody = firstField.parent();
        while (!tbody.is("tbody")) {
            tbody = tbody.parent();
        }
        if (rows.length > oldLength) {
            for (var i = 0; i < (rows.length - oldLength); i++) {
                upWindow.fy_addEmpty(tbody.children().last());
            }
        }
        if (rows.length < oldLength) {
            for (var i = oldLength - rows.length - 1; i >= 0; i--) {
                upWindow.fy_delCurrentRepeat(tbody.children().last());
            }

        }
        var allrepeatFields = firstField.parent("tbody").find(".edit_class");
        for (var k = 0; k < allrepeatFields.length; k++) {
            setUpFieldValue2(allrepeatFields.eq(k), "");
        }

        for (var i = 0; i < rows.length; i++) {
            for (var key in rows[i]) {
                try {
                    setUpFieldValue2(getUpFieldsByFieldval(key).eq(i),
                            rows[i][key]);
                    // $2("my:" + key)[i].value = rows[i][key];
                } catch (e) {
                }
            }
        }
    } else {
        for (var i = 0; i < rows.length; i++) {
            var queryFields = getUpFieldsByFieldval(rows[i].QUERYFIELDNAME);
            for (var j = 0; j < queryFields.length; j++) {
                if (getUpFieldValue(queryFields.eq(j)).value == rows[i][rows[i].QUERYFIELDNAME]) {
                    for (var key in rows[i]) {
                        if (key != rows[i].QUERYFIELDNAME
                                && key != "QUERYFIELDNAME") {
                            try {
                                setUpFieldValue2(getUpFieldsByFieldval(key).eq(
                                        j), rows[i][key]);
                            } catch (e) {
                            }
                        }
                    }
                }
            }
        }
    }

}
function writeForm(rows) {
    if (rows) {
        if (rows.length > 1) {
// 多行
            writeRepeatTableField(rows);
        } else {
// 单行
            writeField(rows);
        }
    }
}

function runAfterQuerOperate() {
    if (typeof afterQueryOperate === 'function') {
        afterQueryOperate();
        fy_dialog_close();
    } else {
        setTimeout("runAfterQuerOperate()", 100);
    }
}

function query() {
    var queryName = getUpFieldValue(getUpFieldsByFieldval("queryName").eq(0)).value;
    var argsStr = getUpFieldValue(getUpFieldsByFieldval("args").eq(0)).value;
    var url = "../common.do?method=commQuery" + "&name=" + queryName;
    if (argsStr != "") {
        var args = argsStr.split(",");
        for (var i = 0; i < args.length; i++) {
            var paramName = args[i];
            var param;
            if (paramName.indexOf("{") == -1) {
//                var valueName = "value";
                if (paramName.indexOf("[") == 0) {
                    paramName = paramName.replace('[', '').replace(']', '');
//                    valueName = "default";
                }
                if (getUpFieldsByFieldval(paramName).length == 1) {
                    // 清楚空格后回写
                    param = trim(getUpFieldValue(getUpFieldsByFieldval(
                            paramName).eq(0)).value); // trim($2("my:" +
                    // paramName)[0][valueName]);
                    // $2("my:" + paramName)[0][valueName] = param;
                } else {
                    var paramArray = [];
                    var paramFields = getUpFieldsByFieldval(paramName);
                    for (var j = 0; j < paramFields.length; j++) {
                        var temp = trim(getUpFieldValue(paramFields.eq(j)).value);
                        // $2("my:" + paramName)[j][valueName] = temp;
                        paramArray.push(temp);
                        if (temp == "") {
                            if (!$2("my:允许为空字段")[0]
                                    || $2("my:允许为空字段")[0].value
                                    .indexOf(paramName) == -1) {
                                alert("表单的“" + paramName + "”字段不能为空，请输入");
                                fy_dialog_close();
                                return;
                            }
                        } else if ("§€".indexOf(temp) != -1) {
                            alert("表单的“" + paramName + "”字段不能含有特殊字符串§€");
                            fy_dialog_close();
                            return;
                        }
                    }
                    param = paramArray.join("§€");
                }
                if (param.replace(/ /g, '') == "") {
                    if (getUpFieldsByFieldval("允许为空字段").length == 0
                            || getUpFieldValue(getUpFieldsByFieldval("允许为空字段")).value
                            .indexOf(paramName) == -1) {
                        alert("表单的“" + paramName + "”字段不能为空，请输入");
                        fy_dialog_close();
                        return;
                    }
                }
            } else {
                param = paramName;
            }
            url = url + "&param=" + encodeURIComponent(param);
        }
    }
    _ajax(url, function (data) {
        if (data.success) {
            resetFields(data.fields);
            if (data.children) {
                for (var i = 0; i < data.children.length; i++) {
                    writeForm(data.children[i].rows);
                }
            } else {
                alert(data.msg);
            }

            if (getUpFieldsByFieldval("afterQuery").length > 0) {
                var funcFile = getUpFieldValue(getUpFieldsByFieldval(
                        "afterQuery").eq(0)).value;
                if (funcFile.indexOf("http") != -1) {
                    alert("错误的地址");
                    fy_dialog_close();
                    return;
                }
                document.getElementById("afterQuerySrcipt").src = funcFile;
                runAfterQuerOperate();
            } else {
                fy_dialog_close();
            }
        } else {
            alert(data.msg);
            if (data.fields) {
                resetFields(data.fields);
            }
            fy_dialog_close();
        }
    });
}

window.onload = function () {
    query();
};